const Koa = require('koa');
const KoaRouter = require('koa-router');
const koaBody = require('koa-body');

let users = [
    { id: 1, username: 'dahai' },
    { id: 2, username: 'zMouse' }
];

// 设置一个Access-Control-Allow-Origin白名单列表
const whiteList = [
    'http://localhost:7777',
    'http://localhost:9999'
];

const server = new Koa();

server.use(async (ctx, next) => {
    // 如果有其它源的脚本（xhr）访问了该服务器，默认会受到 同源策略的影响

    if ( whiteList.includes(ctx.headers.origin) ) {
        ctx.set('Access-Control-Allow-Origin', ctx.headers.origin);
        ctx.set('Access-Control-Allow-Credentials', true);

        // 处理预检请求
        if (ctx.method.toLowerCase() === 'options') {
            // 当前有一个预检请求需要处理

            // 允许实际的请求中发送指定的头信息
            ctx.set('Access-Control-Allow-Headers', 'Content-Type');


            ctx.body = '';
        }
        await next();
    } else {
        ctx.body ='';
    }

})

const router = new KoaRouter();

router.get('/users', async (ctx, next) => {

    ctx.body = users;

});

router.post('/user', koaBody(), async (ctx, next) => {
    console.log(ctx.request.body);

    ctx.body = '提交成功';
});

router.post('/login', async (ctx, next) => {

    ctx.cookies.set('uid', 1);
    ctx.body = '登录成功';
});

router.get('/dahai', async (ctx, next) => {

    if (ctx.cookies.get('uid')) {
        ctx.body = '大海现在在峡谷被虐！';
    } else {
        // ctx.throw(401, '不能看');
        ctx.body = '不能看';
    }
});

server.use(router.routes());

server.listen(8888);
